package net.lesscoding.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import net.lesscoding.Const;

/**
 * @author eleven
 * @date 2024/10/29 14:17
 * @apiNote
 */
public class ClientDemo {
    public static void main(String[] args) {
        new Bootstrap()
                .channel(NioSocketChannel.class)
                .group(new NioEventLoopGroup())
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new StringEncoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    // 连接建立的时候触发
                                    @Override
                                    public void channelActive(io.netty.channel.ChannelHandlerContext ctx) throws Exception {
                                        System.out.println("连接成功");
                                        ByteBuf buffer = ctx.alloc().buffer();
                                        ctx.writeAndFlush(buffer.writeBytes("hello world".getBytes()));
                                        super.channelActive(ctx);
                                    }

                                    @Override
                                    public void channelRead(io.netty.channel.ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(msg);
                                    }
                                });
                    }
                })
                .connect(Const.HOST, Const.PORT)
        ;
    }
}
